import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';

interface UseTableOptions {
  fetchData: (params: any) => Promise<any>;
  searchParams?: Record<string, any>;
  defaultPageSize?: number;
}

interface PaginationConfig {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  showTotal: (total: number, range: [number, number]) => string;
}

export const useTable = ({
  fetchData,
  searchParams = {},
  defaultPageSize = 20,
}: UseTableOptions) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<PaginationConfig>({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => 
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
  });

  const fetchTableData = useCallback(async (params = {}) => {
    setLoading(true);
    try {
      const response = await fetchData({
        page: params.page || pagination.current,
        page_size: params.page_size || pagination.pageSize,
        ...searchParams,
        ...params,
      });
      
      setData(response.list || []);
      setPagination(prev => ({
        ...prev,
        total: response.total || 0,
      }));
    } catch (error) {
      message.error('数据加载失败');
      console.error('Table data fetch error:', error);
    } finally {
      setLoading(false);
    }
  }, [fetchData, searchParams]); // 移除 pagination 依赖，避免循环

  // 初始化数据加载
  useEffect(() => {
    fetchTableData();
  }, [searchParams]); // 只依赖 searchParams

  const handleTableChange = (paginationConfig: any, filters?: any, sorter?: any) => {
    const newPagination = {
      current: paginationConfig.current,
      pageSize: paginationConfig.pageSize,
    };
    
    setPagination(prev => ({
      ...prev,
      ...newPagination,
    }));
    
    // 直接调用 fetchTableData 并传入新的分页参数
    fetchTableData({
      page: newPagination.current,
      page_size: newPagination.pageSize,
    });
  };

  const refresh = () => {
    fetchTableData();
  };

  const handleSearch = (searchData: Record<string, any>) => {
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchTableData({ ...searchData, page: 1 });
  };

  const resetSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchTableData({ page: 1 });
  };

  return {
    data,
    loading,
    pagination,
    refresh,
    handleTableChange,
    handleSearch,
    resetSearch,
  };
};